//Three States
#include<iostream>
#include<deque>
#include<cstring>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 1e3 + 10;
char c[N][N];
int disc[4][N][N];
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};
int m , n;
void bfs(int num)
{
	memset(disc[num],-1,sizeof disc[num]);
	deque<PII> q;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			if(c[i][j] - '0' == num)
			{
				q.push_front({i,j});
				disc[num][i][j] = 0;
			}
		}
	}
	while(q.size())
	{
		auto t = q.front();q.pop_front();
		int i = t.first , j = t.second;
		for(int k = 0; k < 4; k++)
		{
			int x = i + dx[k] , y = j + dy[k];
			if(x >= 1 && x <= n && y >= 1 && y <= m && c[x][y]!='#')
			{
				int w = (c[x][y] == '.' ? 1 : 0);
				if(disc[num][x][y] == -1)
				{
					disc[num][x][y] = disc[num][i][j] + w;
					if(w == 0) q.push_front({x,y});
					else q.push_back({x,y});
				}
				else if(disc[num][i][j] + w < disc[num][x][y])
				{
					disc[num][x][y] = disc[num][i][j] + w;
				}
			}
		}
	}
	
}
int main()
{
	cin >> n >> m;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			cin >> c[i][j];
		}
	}
	bfs(1);bfs(2);bfs(3);
	int ret = 0x3f3f3f;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= m; j++)
		{
			int x = disc[1][i][j], y = disc[2][i][j] , z = disc[3][i][j];
			if(x == -1 || y == -1 || z == -1) continue;
			if(c[i][j] == '#') continue;
			if(c[i][j] == '.') ret = min(ret,x + y + z - 2);
			else ret = min(ret, x + y + z);
		}
	}
	if(ret == 0x3f3f3f) cout << -1;
	else cout << ret;
	return 0;
}
